package com.example.canvas_sign_lib;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class CanvasSignActivity extends AppCompatActivity implements View.OnClickListener {

    private String TAG = "CanvasSignActivity";
    //模板图像
    private ImageView stencilImage;
    //签名画布
    private RelativeLayout signatureCanvas;
    //镂空模板图片
    private Bitmap bitmap;
    //签名画布图片
    private Bitmap signatureCanvasBitmap;

    ImageView signatureCanvasBitmapImage;

    EditText editText01;

    TextView result_text;
    Bundle _savedInstanceState;

    SignatureView signatureView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate============== 01 ");
        _savedInstanceState = savedInstanceState;
        setContentView(R.layout.activity_canvas_sign);
        Log.d(TAG, "onCreate============== 02 ");
        Button button01 = findViewById(R.id.make_bitmap);
        Button button02 = findViewById(R.id.check_bitmap);
        Button button03 = findViewById(R.id.make_null_bitmap);
        Log.d(TAG, "onCreate============== 03 ");
        Button button04 = findViewById(R.id.reset_data);
        result_text = findViewById(R.id.result_text);
        editText01 = findViewById(R.id.edit_null_text);
        Log.d(TAG, "onCreate============== 04 ");
        editText01.setText("大");
        Log.d(TAG, "onCreate============== 05 ");
        signatureCanvasBitmapImage = findViewById(R.id.signatureCanvasBitmapImage);
        Log.d(TAG, "onCreate============== 06 ");
        button01.setOnClickListener(this);
        button02.setOnClickListener(this);
        button03.setOnClickListener(this);
        button04.setOnClickListener(this);
        stencilImage = findViewById(R.id.stencilImage);
        signatureCanvas = findViewById(R.id.signatureCanvas);
        Log.d(TAG, "onCreate============== 07 ");
        signatureView = new SignatureView(this);
        signatureCanvas.addView(signatureView);
        Log.d(TAG, "onCreate============== 08 ");
    }

    private Bitmap generateBitmapWithText(String text, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // 绘制背景透明
        canvas.drawColor(Color.TRANSPARENT);

        // 创建 Paint 对象
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLACK);
        paint.setTextSize(getTextSize(width, height)); // 设置文字大小

        // 计算文字的宽度和高度
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        float textWidth = paint.measureText(text);
        float textHeight = bounds.height();

        // 计算文字绘制位置
        float x = (width - textWidth) / 2;
        float y = (height + textHeight) / 2;
        // 绘制白色边框
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(Color.WHITE);
        canvas.drawText(text, x, y, paint);
        // 绘制黑色文字
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.BLACK);
        canvas.drawText(text, x, y, paint);
        return bitmap;
    }

    private float getTextSize(int width, int height) {
        // 计算文字大小，设定为宽度和高度的80%大小
        float textSize = Math.min(width, height) * 0.8f;
        return textSize;
    }

    @Override
    public void onClick(View view) {
        Log.d(TAG, "=========id0：");
        int id = view.getId();

        Log.d(TAG, "=========id："+id);

        Log.d(TAG, "=========make_bitmap："+(id == R.id.make_bitmap));
        Log.d(TAG, "=========check_bitmap："+(id == R.id.check_bitmap));
        Log.d(TAG, "=========make_null_bitmap："+(id == R.id.make_null_bitmap));
        Log.d(TAG, "=========reset_data："+(id == R.id.reset_data));

        if (id == R.id.make_bitmap) {
            Log.d(TAG, "=========01");
            signatureCanvasBitmap = Bitmap.createBitmap(signatureCanvas.getWidth(), signatureCanvas.getHeight(), Bitmap.Config.ARGB_8888);
            Log.d(TAG, "=========02");
            Canvas canvas = new Canvas(signatureCanvasBitmap);
            canvas.drawColor(Color.TRANSPARENT);
            Log.d(TAG, "=========03");
            signatureCanvas.draw(canvas);
            Log.d(TAG, "=========06");
            signatureCanvasBitmapImage.setImageBitmap(signatureCanvasBitmap);
        } else if (id == R.id.check_bitmap) {
            calculateOverlapPercentage(bitmap, signatureCanvasBitmap);
        } else if (id == R.id.make_null_bitmap) {
            Log.d(TAG, "make_null_bitmap=========01");

            // 生成文字
            String text = "";
            Log.d(TAG, "make_null_bitmap=========02");


            text = editText01.getText().toString();
            Log.d(TAG, "make_null_bitmap=========03");//18953 18953
            bitmap = generateBitmapWithText(text, 400, 400);

            int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            int num = 0;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitmap.getPixel(x, y) != 0) {
                        num++;
                    }
                }
            }


            Log.d(TAG, "make_null_bitmap=========num" + num);
            // 将生成的 Bitmap 设置给 ImageView
            stencilImage.setImageBitmap(bitmap);
        } else if (id == R.id.reset_data) {
            Log.d(TAG, "jarSDK=========返回值01：");
        }
    }

    //重复度检测
    // 计算重合像素的百分比
    public double calculateOverlapPercentage(Bitmap bitmap1, Bitmap bitmap2) {

        Log.d(TAG,"calculateOverlapPercentage=========01 "+bitmap1.getHeight()+""+bitmap1.getWidth());
        Log.d(TAG,"calculateOverlapPercentage=========02 "+bitmap2.getHeight()+""+bitmap2.getWidth());

        //获取宽度和高度
        int width = Math.min(bitmap1.getWidth(), bitmap2.getWidth());
        int height = Math.min(bitmap1.getHeight(), bitmap2.getHeight());

        //重合数
        int totalPixels = 0;
        //总数
        int overlapPixels = 0;
        Log.d(TAG, "calculateOverlapPercentage=======006: width = " + width + ", height = " + height + ", totalPixels = " + totalPixels + ", overlapPixels = " + overlapPixels);

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {

//                Log.d(TAG,""+"x："+x+"y"+y);

                int pixel1 = bitmap1.getPixel(x, y);
                int pixel2 = bitmap2.getPixel(x, y);

                if (isSimilarPixel(pixel1, pixel2)) {
                    overlapPixels++;
                }

                if (isHavePixelColor(pixel1)) {
                    //总数叠加
                    totalPixels++;
                }

            }
        }

        Log.d(TAG, "calculateOverlapPercentage=======007: overlapPixels " + overlapPixels);
        Log.d(TAG, "calculateOverlapPercentage=======008: totalPixels " + totalPixels);

        // 计算重合像素的百分比
        if (totalPixels == 0) {
            return 0;
        }
        //重复率
        double overlapPercentage = (double) overlapPixels / totalPixels * 100;
        Log.d(TAG, "calculateOverlapPercentage=======009: overlapPercentage " + overlapPercentage);


        if(overlapPercentage>80){
            Toast.makeText(getApplicationContext(),"通过",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getApplicationContext(),"未通过",Toast.LENGTH_LONG).show();
        }


        result_text.setText("重合数:"+overlapPixels+"总数:"+totalPixels+"重合率:"+overlapPercentage);
        return overlapPercentage;
    }

    // 判断两个像素是否相似
    private static boolean isSimilarPixel(int pixel1, int pixel2) {
        // 判断两个像素是否相似
        return pixel1 != 0 && pixel2 != 0;
    }

    // 判断像素是否存在颜色
    private static boolean isHavePixelColor(int pixel) {
        return pixel != 0;
    }

//    // 判断两个像素是否相似
//    private static boolean isSimilarPixel(int pixel1, int pixel2) {
//        // 判断两个像素是否相似
//        return pixel1 == Color.BLACK && pixel2 == Color.WHITE;
//    }
//
//    // 判断像素是否存在颜色
//    private static boolean isHavePixelColor(int pixel) {
//        return pixel == Color.BLACK;
//    }

}